using System;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using WpfMedia = System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Interop;
using System.Windows.Media;
using TxTReader.Services;

namespace TxTReader.UI
{
    /// <summary>
    /// AboutWindow.xaml 的交互逻辑
    /// </summary>
    public partial class AboutWindow : Window
    {
        public AboutWindow()
        {
            InitializeComponent();
            
            // 设置窗口图标（信息图标）
            SetWindowIcon();
            
            // 订阅主题变化事件
            ThemeService.ThemeChanged += OnThemeChanged;
            
            // 在窗口加载完成后应用主题
            Loaded += (s, e) => ApplyTheme(ThemeService.GetCurrentTheme());
        }
        
        /// <summary>
        /// 窗口关闭时取消主题订阅
        /// </summary>
        protected override void OnClosed(EventArgs e)
        {
            ThemeService.ThemeChanged -= OnThemeChanged;
            base.OnClosed(e);
        }
        
        /// <summary>
        /// 设置窗口图标（信息图标）
        /// </summary>
        private void SetWindowIcon(System.Drawing.Icon? icon = null)
        {
            try
            {
                // 创建信息图标（圆形 + i字母）
                // 使用Path绘制：圆形 + 字母i
                var infoPath = "M12,2 C6.48,2 2,6.48 2,12 C2,17.52 6.48,22 12,22 C17.52,22 22,17.52 22,12 C22,6.48 17.52,2 12,2 Z M13,17 L11,17 L11,11 L13,11 Z M12,9 C11.45,9 11,8.55 11,8 C11,7.45 11.45,7 12,7 C12.55,7 13,7.45 13,8 C13,8.55 12.55,9 12,9 Z";
                var geometry = Geometry.Parse(infoPath);
                var drawing = new GeometryDrawing(
                    new SolidColorBrush(System.Windows.Media.Color.FromRgb(33, 150, 243)), // 蓝色填充
                    new System.Windows.Media.Pen(new SolidColorBrush(System.Windows.Media.Color.FromRgb(25, 118, 210)), 1.5), // 深蓝色边框
                    geometry);
                
                var drawingGroup = new DrawingGroup();
                drawingGroup.Children.Add(drawing);
                
                var drawingImage = new DrawingImage(drawingGroup);
                drawingImage.Freeze();
                
                // 将DrawingImage转换为BitmapSource并缩放为图标大小
                var renderTarget = new RenderTargetBitmap(32, 32, 96, 96, PixelFormats.Pbgra32);
                var visual = new DrawingVisual();
                using (var context = visual.RenderOpen())
                {
                    context.DrawImage(drawingImage, new Rect(0, 0, 32, 32));
                }
                renderTarget.Render(visual);
                renderTarget.Freeze();
                
                Icon = renderTarget;
            }
            catch
            {
                // 如果设置图标失败，使用系统默认图标
                try
                {
                    if (icon != null)
                    {
                        Icon = Imaging.CreateBitmapSourceFromHIcon(
                            icon.Handle,
                            Int32Rect.Empty,
                            BitmapSizeOptions.FromEmptyOptions());
                    }
                }
                catch { }
            }
        }
        
        /// <summary>
        /// 主题变化事件处理
        /// </summary>
        private void OnThemeChanged(ThemeInfo theme)
        {
            Dispatcher.Invoke(() => ApplyTheme(theme));
        }
        
        /// <summary>
        /// 计算与背景色对比鲜明的文本颜色
        /// </summary>
        private WpfMedia.Brush GetContrastColor(WpfMedia.Brush backgroundBrush)
        {
            if (backgroundBrush is WpfMedia.SolidColorBrush solidBrush)
            {
                var color = solidBrush.Color;
                // 计算相对亮度 (Rec. 709 标准)
                double luminance = 0.2126 * color.R / 255.0 + 0.7152 * color.G / 255.0 + 0.0722 * color.B / 255.0;
                
                // 如果背景较暗，使用亮色文本；如果背景较亮，使用暗色文本
                if (luminance < 0.5)
                {
                    // 背景较暗，使用亮色文本
                    return new WpfMedia.SolidColorBrush(WpfMedia.Color.FromRgb(255, 255, 255));
                }
                else
                {
                    // 背景较亮，使用暗色文本
                    return new WpfMedia.SolidColorBrush(WpfMedia.Color.FromRgb(0, 0, 0));
                }
            }
            // 如果不是SolidColorBrush，返回默认颜色
            return WpfMedia.Brushes.Black;
        }
        
        /// <summary>
        /// 应用主题
        /// </summary>
        private void ApplyTheme(ThemeInfo theme)
        {
            // 应用窗口背景
            Background = theme.WindowBackground;
            
            // 根据背景计算对比鲜明的文本颜色
            var contrastForeground = GetContrastColor(theme.WindowBackground);
            
            // 显式处理按钮（包括边框和背景）
            if (OkButton != null)
            {
                OkButton.Foreground = contrastForeground;
                OkButton.BorderBrush = theme.MenuBackground;
                OkButton.Background = theme.MenuBackground;
            }
            
            // 应用文本颜色到所有TextBlock（使用对比色）
            ApplyControlTheme(this, contrastForeground, theme);
        }
        
        /// <summary>
        /// 递归应用主题到控件
        /// </summary>
        private void ApplyControlTheme(DependencyObject element, WpfMedia.Brush contrastForeground, ThemeInfo theme)
        {
            if (element == null) return;
            
            // 应用TextBlock的前景色（使用对比色）
            if (element is System.Windows.Controls.TextBlock textBlock)
            {
                textBlock.Foreground = contrastForeground;
            }
            else if (element is Button button && theme != null)
            {
                // 处理其他按钮的边框和背景（OkButton已经在ApplyTheme中处理）
                if (button != OkButton)
                {
                    button.Foreground = contrastForeground;
                    button.BorderBrush = theme.MenuBackground;
                    button.Background = theme.MenuBackground;
                }
            }
            
            // 递归处理子元素
            int childCount = VisualTreeHelper.GetChildrenCount(element);
            for (int i = 0; i < childCount; i++)
            {
                var child = VisualTreeHelper.GetChild(element, i);
                ApplyControlTheme(child, contrastForeground, theme);
            }
        }

        private void OnOkClick(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
